'use strict'

/**
 * Expose compositor.
 */

module.exports = compose

/**
 * Compose `middleware` returning
 * a fully valid middleware comprised
 * of all those which are passed.
 *
 * @param {Array} middleware => middleware 存储的是中间件方法数组，里面会有 next()
 * @return {Function}
 * @api public
 */

function compose (middleware) {
  if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')
  for (const fn of middleware) {
    if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
  }

  /**
   * @param {Object} context
   * @return {Promise}
   * @api public
   */

  return function (context, next) {
    // last called middleware #
    let index = -1
    return dispatch(0)

    function dispatch (i) {
      if (i <= index) return Promise.reject(new Error('next() called multiple times'))
      index = i
      let fn = middleware[i]
      if (i === middleware.length) fn = next
      if (!fn) return Promise.resolve()
      try {
        // fn(context, dispatch.bind(null, i + 1)) 为执行中间件方法
        // dispatch.bind(null, i + 1) 对应中间件中的 next
        return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
      } catch (err) {
        return Promise.reject(err)
      }
    }

  }
}

// let fn = middleware[i]
// fn 对应的就是 one、two、three

// const one = (ctx, next) => {
//   console.log('>> one');
//   next();
//   console.log('<< one');
// }
// const two = (ctx, next) => {
//   console.log('>> two');
//   next(); 
//   console.log('<< two');
// }
// const three = (ctx, next) => {
//   console.log('>> three');
//   next();
//   console.log('<< three');
// }
// app.use(one);
// app.use(two);
// app.use(three);